package com.lzk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzk.common.R;
import com.lzk.mapper.UserMapper;
import com.lzk.pojo.User;
import com.lzk.service.UserService;
import com.lzk.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserService userService;
    @Override
    public R<String> sendMsg(User user, HttpSession session) {
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("验证码为：{}", code);
        if (StringUtils.isEmpty(code)) {
            return R.error("验证码发送失败");
        }
        session.setAttribute(phone, code);
        return R.success("验证码发送成功");
    }

    @Override
    public R<User> login(Map<String, Object> map, HttpSession session) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        String trueCode = (String) session.getAttribute(phone);
        if (!trueCode.equals(code)) {
            return R.error("验证码错误");
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(userLambdaQueryWrapper);
        if (user == null){
            user=new User();
            user.setPhone(phone);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        return R.success(user);
    }

}
